package 
{
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.system.System;
	import flash.ui.ContextMenu;
	import flash.utils.ByteArray;
	import flash.utils.escapeMultiByte;
	
	import global.GameState;
	
	import start.LoadingTool;
	import start.StartLoading;

	[SWF(width="780",height="770",backgroundColor="#000000")]
	public class Loading extends Sprite
	{
		private var urlLoader:URLLoader; 
		private var loginLoader:URLLoader;
		private var otherLoader:Loader;
		private var loadStack:Array = ["GanDengYan.swf","component.swf","effect.swf"];
		private var xmlLoadStack:Array = [];
		
		private var currentLoadUrl:String = "";
		private var lastLoadUrl:String;
		private var main:Object;
		
		
		
		private var loadingTool:LoadingTool;
		
		private var total:int;
		private var currentTotal:int;
		private var current:int;
		
		private var startLoading:StartLoading;
		
		[Embed(source="resource/logo.swf")]
		private var logoClass:Class;
		
		private var logo:DisplayObject;
		
		public function Loading()
		{
			
			initStage();
			initStartLoading();
			total = 150000;
			loadConfig();
			
			System.useCodePage = true;
		}
		
		private function initLogin():void
		{
			if (this.root.loaderInfo.parameters["debug"] == "0")
			{
				loginLoader = new URLLoader();
				loginLoader.addEventListener(Event.COMPLETE,onLoginComplete);
				loginLoader.dataFormat = URLLoaderDataFormat.BINARY;
				loginLoader.load(new URLRequest(GameState.getServerLink() + "16&key=" + GameState.snsKey));
				
			}
		}
		
		private function onLoginComplete(event:Event):void
		{
			loginLoader.removeEventListener(Event.COMPLETE,onLoginComplete);
			
			var byteArray:ByteArray = ByteArray(loginLoader.data);
			byteArray.uncompress();
			
			
			GameState.isLogin = true;
			GameState.playerInfoXml = XML(byteArray.readMultiByte(byteArray.bytesAvailable,"utf-16"));
			if (this.main)
			{
				this.main.login();
			}
			loginLoader = null;
		}
	
		
		private function initStartLoading():void
		{
			startLoading = new StartLoading();
			startLoading.x = (GameState.GAME_WIDTH - startLoading.width) *.5;
			startLoading.y = (GameState.GAME_HEIGHT - startLoading.height) *.5 + 70;
			addChild(startLoading);
		}
		
		private function initLoadingTool():void
		{
			loadingTool = new LoadingTool(loadStack.concat(xmlLoadStack));
			loadingTool.addEventListener(Event.COMPLETE,onLoadingToolComplete);
			//loadingTool.load();
			
			
		}
		
		private function onLoadingToolComplete(event:Event):void
		{
			loadingTool.removeEventListener(Event.COMPLETE,onLoadingToolComplete);
			total = loadingTool.total;
			loadingTool = null;
			
			loadConfig();
		}
		
		private function initStage():void
		{
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
			stage.frameRate = 24;
			//stage.quality = StageQuality.MEDIUM;
			var c:ContextMenu = new ContextMenu();
			c.hideBuiltInItems();
			this.contextMenu = c;
		}
		
		private function loadOthers():void
		{
			if (otherLoader == null)
			{
				otherLoader = new Loader();
				otherLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,onOtherLoadError);
				otherLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,onLoadComp);
				otherLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,onProgress);
			}
			
			
			if (loadStack.length > 0)
			{
			
				currentLoadUrl = loadStack.shift();
				if (currentLoadUrl == "GanDengYan.swf")
				{
					otherLoader.load(new URLRequest(currentLoadUrl));
				}
				else
				{
					otherLoader.load(new URLRequest("resource/" + currentLoadUrl));
				}
			}
			else if (xmlLoadStack.length > 0)
			{
				currentLoadUrl = xmlLoadStack.shift();
				urlLoader.load(new URLRequest("resource/" + currentLoadUrl));
			}
			else
			{
				clear();
				main.setLogo(logo);
				main.init();
			}
		}
		
		private function onOtherLoadError(event:IOErrorEvent):void
		{
			trace("other load Error!");
		}
		
		private function loadConfig():void
		{
			urlLoader = new URLLoader();
			urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
			urlLoader.addEventListener(Event.COMPLETE,onLoadComp);
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR,onIOError);
			urlLoader.addEventListener(ProgressEvent.PROGRESS,onProgress);
			
			
			if (this.root.loaderInfo.parameters["debug"] == "0")
			{
				setConfig();
				initLogin();
				loadOthers();
			}
			else
			{
				urlLoader.load(new URLRequest("config.xml"));
			}
			
			
		}
		
		private function onProgress(event:ProgressEvent):void
		{
			current = event.bytesTotal;
			trace((currentTotal + event.bytesLoaded) / total,currentLoadUrl)
			startLoading.percent = (currentTotal + event.bytesLoaded) / total;
			startLoading.text = "Loading..." + currentLoadUrl;
		}
		
		private function onLoadComp(event:Event):void
		{
			
			currentTotal += current;
			
			switch (currentLoadUrl)
			{
				case "":
					setConfig();
					break;
				/*case "fastreplay.xml":
					setFastReply();
					break;*/
				/*case "famous.xml":
					setFamus();
					break;*/
				case "GanDengYan.swf":
					setMain(otherLoader.content);
					break;
				/*case "Resource.swf":
					setResource(otherLoader.content);
					break;*/
				case "component.swf":
					setComponents(otherLoader.content);
					break;
				case "effect.swf":
					setEffect(otherLoader.content);
					break;
				/*case "logo.swf":
					setLogo(otherLoader.content);*/
					break;
			}
			lastLoadUrl = currentLoadUrl;
			loadOthers();
		}
		
		private function setLogo():void
		{
			this.logo = new logoClass();;

			((logo as DisplayObjectContainer).getChildAt(0) as Loader).contentLoaderInfo.addEventListener(Event.COMPLETE,onCO);
			
			function onCO(event:Event):void
			{
				event.target.removeEventListener(Event.COMPLETE,onCO);
				(((logo as DisplayObjectContainer).getChildAt(0) as Loader).content as Object).version.text = GameState.version;
			}
			logo.x = (GameState.GAME_WIDTH - logo.width) * .5 + 10;
			logo.y = 150;
			addChild(logo);
		}
		
		private function setFamus():void
		{
			var xml:XML = XML(urlLoader.data);
			main.setFamus(xml);
		}
		
		private function setFastReply():void
		{
			var xml:XML = XML(urlLoader.data);
			main.setFastReply(xml);
		}
		
		private function convertByteArrayToObjet(ba:ByteArray):DisplayObject
		{
			return null;
		}
		
		private function setEffect(effect:*):void
		{
			main.setEffect(effect);
		}
		
		private function setComponents(component:*):void
		{
			main.setComponents(component);
		}
		
		private function setResource(resource:Object):void
		{
			main.setResource(resource);		
		}
		
		private function setMain(main:Object):void
		{
			this.main = main;
			addChild(main as DisplayObject);
		}
		
		private function setConfig():void
		{
			if (String(this.root.loaderInfo.parameters["debug"]) == "0")
			{
				GameState.DEBUG_STATE = 0;
				GameState.resourceLink = String(this.root.loaderInfo.parameters["resourceLink"]);
				GameState.serverIp = String(this.root.loaderInfo.parameters["server"]);
				GameState.serverPort = int(this.root.loaderInfo.parameters["port"]);
				GameState.traceType = int(this.root.loaderInfo.parameters["tracyType"]);
				GameState.version = this.root.loaderInfo.parameters["version"];
				GameState.snsId = this.root.loaderInfo.parameters["id"];
				GameState.isEscape = this.root.loaderInfo.parameters["isEscape"];
				GameState.inviteLink = this.root.loaderInfo.parameters["inviteLink"];
				GameState.tutorLink = this.root.loaderInfo.parameters["tutorLink"];
				GameState.shopLink = this.root.loaderInfo.parameters["shopLink"];
				if (GameState.isEscape == "1")
				{
					GameState.snsKey = escapeMultiByte(this.root.loaderInfo.parameters["key"]);
				}
				else
				{
					GameState.snsKey = this.root.loaderInfo.parameters["key"];
				}
				GameState.sns = this.root.loaderInfo.parameters["sns"];
				GameState.time = this.root.loaderInfo.parameters["time"];
				GameState.isRobot = this.root.loaderInfo.parameters["isRobot"];
			}
			else
			{
				var configXml:XML = new XML(urlLoader.data);
				GameState.DEBUG_STATE = int(configXml.debug);
				GameState.resourceLink = String(configXml.resourceLink);
				GameState.serverIp = String(configXml.server);
				GameState.serverPort = int(configXml.port);
				GameState.traceType = int(configXml.traceType);
				GameState.sns = String(configXml.sns);
				
				if( GameState.DEBUG_STATE == 1)
				{
					GameState.snsId = GameState.snsKey = String(configXml.snsid);
				}
				GameState.version = String(configXml.version);
				GameState.isRobot = String(configXml.isRobot);
				
			}
			//GameState.sns = "2";
			//GameState.snsId = "1744885204";
			//GameState.snsKey = "4b4c0ba16800d5d4da6fd79441b89aa9";
			urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
			setLogo();
			
			
		}
		
		private function onIOError(event:Event):void
		{
			trace("config loads Error!");
		}
		
		private function clear():void
		{
			otherLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,onOtherLoadError);
			otherLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE,onLoadComp);
			
			urlLoader.removeEventListener(Event.COMPLETE,onLoadComp);
			urlLoader.removeEventListener(IOErrorEvent.IO_ERROR,onIOError);
			
			otherLoader = null;
			urlLoader = null;
			
			removeChild(startLoading);
		}
	}
}